package com.ruoyi.project.bid.controller;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.bid.domain.Category;
import com.ruoyi.project.bid.domain.vo.CategoryVO;
import com.ruoyi.project.bid.domain.vo.CategorySortVO;
import com.ruoyi.project.bid.service.ICategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;

/**
 * 行业类别
 */
@Api(tags = "行业类别")
@RestController
@RequestMapping("/category")
public class CategoryController extends BaseController
{
    @Autowired
    private ICategoryService categoryService;


    /**
     * 获取列表
     */
    @PreAuthorize("@ss.hasPermi('selfcom:dept:list')")
    @GetMapping("/list")
    public AjaxResult list(Category dept)
    {
        dept.setComId(SecurityUtils.getCurrComId());
        List<Category> depts = categoryService.selectDeptList(dept);
        return AjaxResult.success(depts);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('selfcom:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId)
    {
        List<Category> depts = categoryService.selectDeptList(new Category());
        Iterator<Category> it = depts.iterator();
        while (it.hasNext())
        {
            Category d = (Category) it.next();
            if (d.getCategoryId().intValue() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""))
            {
                it.remove();
            }
        }
        return AjaxResult.success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('selfcom:dept:query')")
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId)
    {
        return AjaxResult.success(categoryService.selectDeptById(deptId));
    }

    /**
     * 获取部门下拉树列表
     */
    @ApiOperation("树形列表")
    @GetMapping("/tree")
    public AjaxResult treeselect(String name)
    {
        Category dept = new Category();
        dept.setCategoryName(name);
        dept.setComId(SecurityUtils.getCurrComId());
        List<Category> depts = categoryService.selectDeptList(dept);

        // 非超级管理员，处理行业权限
        if (!SecurityUtils.isComAdmin()) {
            // 用户拥有的ids，即行业权限ids
            String ids = SecurityUtils.getLoginUser().getUser().getIds();
            String[] idsArray = StringUtils.split(ids, ",");
            // 不在ids内的全部删除
            Iterator<Category> it = depts.iterator();
            while (it.hasNext()) {
                Category d = (Category) it.next();
                if (!ArrayUtils.contains(idsArray, d.getCategoryId() + "")) {
                    it.remove();
                }
            }
        }
        return AjaxResult.success(categoryService.buildSortTree(depts));
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public AjaxResult roleDeptTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<Category> depts = categoryService.selectDeptList(new Category());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", categoryService.selectDeptListByRoleId(roleId));
        ajax.put("depts", categoryService.buildDeptTreeSelect(depts));
        return ajax;
    }

    /**
     * 新增行业
     */
    @ApiOperation("新增行业")
    @PreAuthorize("@ss.hasPermi('selfcom:dept:add')")
    @Log(title = "行业管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody CategoryVO dept)
    {
        Category category = new Category();
        category.setCategoryName(dept.getCategoryName());
        category.setParentId(dept.getParentId());
        category.setCreateBy(SecurityUtils.getUsername());
        return toAjax(categoryService.insertDept(category));
    }

    /**
     * 修改行业
     */
    @ApiOperation("修改行业")
    @PreAuthorize("@ss.hasPermi('selfcom:dept:edit')")
    @Log(title = "行业管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody CategoryVO dept)
    {
        if (dept.getParentId().equals(dept.getCategoryId()))
        {
            return AjaxResult.error("修改部门'" + dept.getCategoryName() + "'失败，上级部门不能是自己");
        }

        Category category = new Category();
        category.setCategoryId(dept.getCategoryId());
        category.setParentId(dept.getParentId());
        category.setCategoryName(dept.getCategoryName());
        category.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(categoryService.updateDept(category));
    }

    /**
     * 删除行业
     */
    @ApiOperation("删除行业")
    @PreAuthorize("@ss.hasPermi('selfcom:dept:remove')")
    @Log(title = "行业管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{categoryId}")
    public AjaxResult remove(@PathVariable Long categoryId)
    {
        if (categoryService.hasChildByDeptId(categoryId))
        {
            return AjaxResult.error("存在下级部门,不允许删除");
        }
        return toAjax(categoryService.deleteDeptById(categoryId));
    }

    /**
     * 排序
     */
    @ApiOperation("行业排序")
    @Log(title = "行业管理", businessType = BusinessType.OTHER)
    @PostMapping("sort")
    public AjaxResult sort(@Validated @RequestBody CategorySortVO dept)
    {
        return toAjax(categoryService.sortCategory(dept.getPid(), dept.getIds()));
    }
}
